/**
 * @Author: xzm
 * @Date: 2019/9/10
 */
import _ from 'lodash';
const getLocalRegion = () => {
    return JSON.parse(localStorage.getItem('region')) || {};
};

export const region = {
    data() {
        return {
            "regionList":[]
        }
    },
    beforeCreate() {
        this.region = getLocalRegion();
        if (!Object.keys(this.region).length) {
          return this.$notify({
            title: '提示信息',
            message: '本地区域信息被清空，请刷新当前页面',
            type: 'warning'
          });
        }
      },
    methods: {
        createRegionText(regionId) {
            let res = '';
            if (!regionId) return res;
            if(this.regionList==null || this.regionList.length<1)
                this.regionList = this.getRegionList(this.region);
            if (_.isArray(this.regionList)) {
              res = (this.regionList.find(x => x.regionId == regionId) || {}).regionName;
            }
            return res;
        },
        createRegionList() {
            let res = [];
            if (_.isObject(this.region)) {
                for (let i in this.region) {
                res.push({ text: this.region[i].regionName, value: this.region[i].regionId });
                }
            }
            return res;
        },
        createSubRegionList(subRegion){
            let res = [];
            if (_.isObject(subRegion)) {
                for (let i in subRegion) {
                    res.push({ text: subRegion[i].regionName, value: subRegion[i].regionId});
                }
            }
            return res;
        },
        getRegionData(){
            return this.region;
        },
        getRegionList(params) {
            let rl = [];
            if(params!=null && Object.keys(this.region).length){
                for(let key in params){
                    let node = params[key];
                    rl.push(node);
                    if(node.children && typeof(node.children)!='undefined' && Object.keys(node.children).length){
                        let crl =this.getRegionList(node.children);
                        if(crl!=null && crl.length>0){
                            for (let skey in crl) {
                                rl.push(crl[skey]);
                            }
                        }
                    }
                }
            }
            return rl;
        }
    }
}